package com.test.io.nio.client;


import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

/**
 * describe:Nio客户端
 *
 *
 * @author lianying
 * @date 2020/01/23
 */
public class NioClient {
    private String host;
    private int port;
    private String clientName;
    private Selector selector;

    public NioClient(String host, int port, String clientName) {
        this.host = host;
        this.port = port;
        this.clientName = clientName;
    }

    private SocketChannel socketChannel;
    public void start() throws IOException {
        socketChannel=SocketChannel.open(new InetSocketAddress(host,port));
        socketChannel.configureBlocking(false);
        selector=Selector.open();
        socketChannel.register(selector, SelectionKey.OP_READ);
        new Thread(){
            @Override
            public void run() {
                try {
                    while (true)
                    {
                        Thread.sleep(100);
                        int i=selector.select();
                        if(i==0)
                        {
                            continue;
                        }
                        Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                        while (iterator.hasNext())
                        {
                            SelectionKey next = iterator.next();
                            iterator.remove();
                            if(next.channel() instanceof SocketChannel)
                            {
                                readHandler(next);
                            }
                        }
                    }
                }catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        }.start();
        Scanner scanner=new Scanner(System.in);
        while (true)
        {
            String s = scanner.nextLine();
            if(s!=null&s.length()>0)
            {
                socketChannel.write(Charset.forName("UTF-8").encode(clientName+":"+s));
            }
        }
    }

    private void readHandler(SelectionKey selectionKey) throws IOException {
        //读取数据进行群发
        SocketChannel read= (SocketChannel) selectionKey.channel();
        ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
        String response="";
        while (read.read(byteBuffer)>0)
        {
            byteBuffer.flip();
            response+=Charset.forName("UTF-8").decode(byteBuffer);
        }
        if(response.length()>0)
        {
            System.out.println(response);
        }
    }
}
